package com.fafa.yygh.hosp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.fafa.yygh.cmn.client.DictFeignClient;
import com.fafa.yygh.enums.DictEnum;
import com.fafa.yygh.hosp.repository.DepartmentRepository;
import com.fafa.yygh.hosp.service.HospitalService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fafa.yygh.hosp.mapper.HospitalSetMapper;
import com.fafa.yygh.hosp.repository.HospitalRepository;
import com.fafa.yygh.model.hosp.BookingRule;
import com.fafa.yygh.model.hosp.Hospital;
import com.fafa.yygh.model.hosp.HospitalSet;
import com.fafa.yygh.vo.hosp.HospitalQueryVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Sire
 * @version 1.0
 * @date 2022-02-10 15:00
 */
@Slf4j
@Service
public class HospitalServiceImpl implements HospitalService {

    @Autowired
    private HospitalRepository hospitalRepository;

    @Autowired
    private DictFeignClient dictFeignClient;

    /**
     * 上传医院系信息
     * 增加或更新
     *
     * @param paramMap
     */
    @Override
    public void save(Map<String, Object> paramMap) {
        log.info(JSONObject.toJSONString(paramMap));
        // 先将map转换成字符串
        String s = JSONObject.toJSONString(paramMap);
        // 将其转成对象
        Hospital hospital = JSONObject.parseObject(s, Hospital.class);
        Hospital targetHospital = hospitalRepository.getHospitalByHoscode(hospital.getHoscode());
        // 如果mongoDB中没有则进行添加操作,否则进行更新操作
        // 需要注意的是这里进行set的都是 BaseMongoEntity 里的属性
        if (targetHospital != null) {
            // 更新操作
            hospital.setStatus(targetHospital.getStatus());
            hospital.setCreateTime(targetHospital.getCreateTime());
            hospital.setUpdateTime(new Date());
            hospital.setIsDeleted(0);
            hospitalRepository.save(hospital);
        } else {
            // 添加操作
            hospital.setCreateTime(new Date());
            hospital.setUpdateTime(new Date());
            hospital.setIsDeleted(0);
            hospitalRepository.save(hospital);
        }
    }

    /**
     * 查询医院接口
     *
     * @param hoscode
     * @return
     */
    @Override
    public Hospital getByHoscode(String hoscode) {
        return hospitalRepository.getHospitalByHoscode(hoscode);
    }

    /**
     * 分页查询医院信息
     *
     * @param page
     * @param limit
     * @param hospitalQueryVo
     * @return
     */
    @Override
    public Page<Hospital> selectPage(Integer page, Integer limit, HospitalQueryVo hospitalQueryVo) {
        Sort sort = Sort.by(Sort.Direction.DESC, "createTime");
        Pageable pageable = PageRequest.of(page - 1, limit, sort);
        // 复制对象（VO对象只负责传输）
        Hospital hospital = new Hospital();
        BeanUtils.copyProperties(hospitalQueryVo, hospital);
        // 模糊查询
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
                .withIgnoreCase(true);
        Example<Hospital> example = Example.of(hospital, matcher);
        // 调用repository
        Page<Hospital> pages = hospitalRepository.findAll(example, pageable);
        // 使用JDK8的新特性进行遍历（Stream流）
        pages.getContent().stream().forEach(item -> {
            // 将一些额外参数赋值（不会存到数据库的，仅用于前端显示）
            this.packHospital(item);
        });
        return pages;
    }

    /**
     * 更新医院状态
     *
     * @param id
     * @param status
     */
    @Override
    public void updateStatus(String id, Integer status) {
        if (status == 0 || status == 1) {
            Hospital hospital = hospitalRepository.findById(id).get();
            hospital.setStatus(status);
            hospital.setUpdateTime(new Date());
            hospitalRepository.save(hospital);
        }
    }

    /**
     * 展示医院信息
     *
     * @param id
     * @return
     */
    @Override
    public Map<String, Object> show(String id) {
        HashMap<String, Object> map = new HashMap<>();
        Hospital hospital = hospitalRepository.findById(id).get();
        // 将 医院信息 和 省市区等信息赋值
        this.packHospital(hospital);
        // 将预约规则抽离出来（分成预约规则，和医院两部分）
        BookingRule bookingRule = hospital.getBookingRule();
        // 不需要重复返回
        hospital.setBookingRule(null);
        //单独处理更直观
        map.put("hospital", hospital);
        map.put("bookingRule", bookingRule);
        return map;
    }

    /**
     * 封装数据
     *
     * @param hospital
     * @return
     */
    public Hospital packHospital(Hospital hospital) {
        // 医院类型
        String hosTypeString = dictFeignClient.getName(DictEnum.HOSTYPE.getDictCode(), hospital.getHostype());
        String provinceString = dictFeignClient.getName(hospital.getProvinceCode());
        String cityString = dictFeignClient.getName(hospital.getCityCode());
        String addressString = dictFeignClient.getName(hospital.getDistrictCode());
        // 医院类型
        hospital.getParam().put("hosTypeString", hosTypeString);
        // 地址
        hospital.getParam().put("fullAddress", provinceString + cityString + addressString);
        return hospital;
    }

    /**
     * 根据医院编号获取医院名称接口
     *
     * @param hoscode
     * @return
     */
    @Override
    public String getHospName(String hoscode) {
        Hospital hospital = hospitalRepository.getHospitalByHoscode(hoscode);
        if (null != hospital) {
            return hospital.getHosname();
        }
        return "";
    }

    /**
     * 根据医院名称获取医院列表
     *
     * @param hosname
     * @return
     */
    @Override
    public List<Hospital> findByHosname(String hosname) {
        // 调用 mongoDb 生成的 方法（遵循spring-data命名规范）
        List<Hospital> list = hospitalRepository.findHospitalByHosnameLike(hosname);
        return list;
    }

    /**
     * 医院预约挂号详情
     * 和展示医院功能类似
     *
     * @param hoscode
     * @return
     */
    @Override
    public Map<String, Object> item(String hoscode) {
        Map<String, Object> result = new HashMap<>();
        Hospital hospital = this.getByHoscode(hoscode);
        // 将 医院信息 和 省市区等信息赋值
        this.packHospital(hospital);
        result.put("hospital", hospital);
        result.put("bookingRule", hospital.getBookingRule());
        //不需要重复返回
        hospital.setBookingRule(null);
        return result;
    }


}
